import QueryList from '@/components/basicWidget/QueryList'
import { _delete, post } from '@/utils/requestUtil'
import { Modal, message } from 'antd'
import React, { Component } from 'react'

class HomePageRecommend extends Component {

    constructor(props) {
        super(props)
        this.state = {
            modalVisual: false,
            modalKey: new Date().getTime() + ''
        }
    }

    async componentDidMount() {

    }

    onAdd = async () => {
        await new Promise(resolve => {
            this.setState({
                modalVisual: true,
                modalKey: new Date().getTime() + ''
            }, resolve)
        })
    }

    cancelHandler = async () => {
        await new Promise(resolve => { this.setState({ modalVisual: false }, resolve) })
    }

    onDelete = async () => {
        const { selectedRowKeys } = this.queryList.state
        if (selectedRowKeys.length === 0) {
            message.warning('请选择数据')
            return
        }
        const response = await _delete('/blog/remove/recommend', {
            body: JSON.stringify(selectedRowKeys)
        })
        if (response && response.code === 200) {
            await this.queryList.onQuery()
            message.success('操作成功')
        } else {
            message.warning('操作失败，请联系关联')
        }
    }

    onSelectFinish = async () => {
        const { selectedRowKeys } = this.modalQueryList.state
        if (selectedRowKeys.length === 0) {
            message.warning('请选择数据')
            return
        }
        const response = await post('/blog/add/recommend', {
            body: JSON.stringify(selectedRowKeys)
        })
        if (response && response.code === 200) {
            await this.queryList.onQuery()
            await this.cancelHandler()
            message.success('操作成功')
        } else {
            message.warning('操作失败，请联系关联')
        }
    }

    //渲染博客推荐选择modal框
    renderSelectModal = () => {
        return (
            <Modal
                title='博客选择'
                open={this.state.modalVisual}
                onCancel={this.cancelHandler}
                footer={null}
                width={'80%'}
            >
                <QueryList
                    queryCode='blogChoosePopup'
                    onSelectFinish={this.onSelectFinish}
                    ref={queryList => this.modalQueryList = queryList}
                >
                </QueryList>
            </Modal>
        )
    }

    render() {
        return (
            <>
                <QueryList
                    queryCode='homePageRecommend'
                    onAdd={this.onAdd}
                    onDelete={this.onDelete}
                    ref={queryList => this.queryList = queryList}
                >
                </QueryList>
                {this.renderSelectModal()}
            </>
        )
    }
}

export default HomePageRecommend